package com.wcar.sso.controller;

import com.alibaba.fastjson.JSON;
import com.wcar.common.entity.User;
import com.wcar.common.util.WebUtil;
import com.wcar.common.vo.Result;
import com.wcar.sso.vo.LoginVo;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.*;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/userAuth")
public class LoginController {
    @Autowired
    private StringRedisTemplate redisTemplate;
    @PostMapping("/Login")
    public Result Login(@RequestBody LoginVo loginVo) {
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken usernamePasswordToken=new UsernamePasswordToken(loginVo.getUserName(), loginVo.getPassWord());
        try{
            subject.login(usernamePasswordToken);
            String token = UUID.randomUUID().toString().replace("-", "");
            User user = (User) subject.getPrincipal();
            ValueOperations<String, String> opsForValue = redisTemplate.opsForValue();
            opsForValue.set("user:login:"+token, JSON.toJSONString(user),30, TimeUnit.MINUTES);
            return new Result<>(200,"登陆成功",token);
        }catch (Exception e){
            e.printStackTrace();
            return new Result<>(500,"账号密码错误",null);
        }
    }
    @GetMapping("/logout")
    public Result<User> logout(){
        //获取token
        String token = WebUtil.getToken();
        redisTemplate.delete("user:login:"+token);
        return  new Result<User>(200,"退出成功",null);

    }
    @GetMapping("/checkPass")
    public Result<String> checkPass(@RequestParam String passOld){

        //获取token
        String token = WebUtil.getToken();
        ValueOperations<String, String> forValue = redisTemplate.opsForValue();
        String s = forValue.get("user:login:" + token);
        User user = JSON.parseObject(s, User.class);
        Md5Hash md5 = new Md5Hash(passOld,user.getSalt(),5);
        if(!user.getPassword().equals(md5.toString())){
            return new Result<>(500,"原密码错误",null);
        }
        return new Result<String>(200,"原密码正确",null);
    }
    @GetMapping("/info")
    public Result<User> info(){
        //获取token
        String token = WebUtil.getToken();
        ValueOperations<String, String> forValue = redisTemplate.opsForValue();
        String s = forValue.get("user:login:" + token);
        User user = JSON.parseObject(s, User.class);
        return new Result<User>(200,"获取用户信息成功",user);
    }
}
